package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClazzMapper clazzMapper;

    //分页查询
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult<Student> selectConditionStudent(StudentQueryParam student) {
        Page<Student> page = new Page<>(student.getPage(), student.getPageSize());

        //sql: select * from student where name like '%?%' and degree = 1 and clazz_id = 1
        LambdaQueryWrapper<Student> sqw = new LambdaQueryWrapper<>();
        sqw.like(student.getName().length()>0 ,Student::getName,student.getName());
        sqw.eq(student.getDegree() !=null &&student.getDegree() >0 ,Student::getDegree,student.getDegree());
        sqw.eq(student.getClazzId() != null && student.getClazzId() >0,Student::getClazzId,student.getClazzId());


      /*
      此处this指的是StudentServiceImpl 而StudentServiceImpl继承ServiceImpl<StudentMapper, Student>
      * ServiceImpl<StudentMapper, Student>里面有page这个方法
       studentMapper 继承basemapper 而basemapper里面没有page这个方法
       所以用不了page 只能用this.page(page) 调用的是继承自 ServiceImpl 类的方法
       这个方法内部会使用 studentMapper 来执行实际的数据库查询
      *  */
        Page<Student> page1 = this.page(page,sqw);

        List<Student> records = page1.getRecords();
        //从records中找到所有的班级id 并且转换成一个新的集合
        Set<Integer> set = records.stream().map(item -> item.getClazzId()).filter(clazzId -> clazzId != null).collect(Collectors.toSet());
        //判断 如果set集合不为空 则有数据
        if(set.size() > 0 && set != null){
            //根据set集合中的班级id 查询所有的班级信息
            List<Clazz> clazzes = clazzMapper.selectBatchIds(set);

            /*
            * 此时就有两种方法去获取班主任名称
            * 第一种双重循环  第二种map集合转换成map<Interage,ClazzName>
            * */
            //第一种方法
//            for(Student student1 : records){
//                for(Clazz clazz : clazzes){
//                    if(student1!=null && student1.getClazzId() != null && clazz!=null && clazz.getId() != null && student1.getClazzId().equals(clazz.getId())){
//                        student1.setClazzName(clazz.getName());
//                    }
//                }
//            }

            //第二种方法
            Map<Integer, String> collect = clazzes.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            for (Student student1 : records){
                student1.setClazzName(collect.get(student1.getClazzId()));
            }

        }

        PageResult<Student> studentPageResult = new PageResult<>(page1.getTotal(),records);
        return studentPageResult;


    }


    //添加学生
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        /*
        * 思路:
        * 1.判断id是否为空
        * 2.如果id为空 则添加
        * 3.如果id不为空 则根据id找到班主任id 再获取班主任名称
        * 4.将班主任名称设置给班级
        * 5.进行插入数据到数据库李里
        * */
        if(student.getClazzId()!=null){
            //找到班级数据
            Clazz clazz = clazzMapper.selectById(student.getClazzId());
            if(clazz != null){
                //给添加的学生设置班级名称
                student.setClazzName(clazz.getName());
                studentMapper.insert(student);
            }
        }

    }


    //修改学生
    @Override
    public void updateStudentById(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        this.updateById(student);
    }


    //违纪
    @Override
    public void updateStudentScore(Integer id, Integer score) {
        //现根据id查出这个学生数据
        Student student = studentMapper.selectById(id);
        //获取学生违纪分数
        Short violationScore = student.getViolationScore();
        //如果学生违纪分数为空 则设置他为0
        if(violationScore == null){
            violationScore = 0;
        }
        //累加违纪分数(此处需要转换类型)
        student.setViolationScore((short)(violationScore + score));

        //获取学生违纪次数
        Short violationCount = student.getViolationCount();
        //如果学生违纪次数为空 则设置他为0
        if(violationCount == null){
            violationCount = 0;
        }
        //累加违纪次数
        student.setViolationCount((short)(violationCount + 1));

        // 更新学生信息到数据库
        student.setUpdateTime(LocalDateTime.now());
        this.updateById(student);
    }
}
